import { message, Upload } from 'antd';
import React, { useState } from 'react';
import less from './simple.less';
import beforeUpload from './beforeUpload';
import uploadUrl from './uploadUrl';

const SimpleUpload = props => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState({});
  const { render, children, className, onChange, ...others } = props;
  const handleChange = info => {
    if (!loading) {
      setLoading(true);
    }
    const { name: FileName, size: FileSize } = info.file;
    if (info.file.status === 'done') {
      if (loading) {
        setLoading(false);
      }
      if (info.file.response && info.file.response.SuccessResponse) {
        message.success(`${info.file.name} 文件上传成功`);
        const value = {
          FileName,
          FileSize,
          URL: info.file.response.Data.Url,
        };
        setData(value);
        onChange && onChange(value);
        props.success && props.success(value);
      } else {
        message.error(`${info.file.name} 文件上传失败.`);
      }
    }
  };
  return (
    <Upload
      disabled={loading}
      className={`${less.simple} ${className}`}
      beforeUpload={beforeUpload(props)}
      action={uploadUrl}
      onChange={handleChange}
      {...others}
    >
      {render && render(loading, data)}
      {!render && props.children}
    </Upload>
  );
};
export default SimpleUpload;
